import axios from 'axios';
import Message from 'element-ui/packages/message/src/main';

function num45Filter(amount, decimalCount = 2, decimal = '.', thousands = '') {
    try {
        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

        const negativeSign = amount < 0 ? '-' : '';
        let tempVal = Math.pow(10, 2);
        let i = parseInt(
            (amount = Math.abs(
                Number(Math.round(amount * tempVal) / tempVal) || 0
            ).toFixed(decimalCount))
        ).toString();
        let j = i.length > 3 ? i.length % 3 : 0;

        return (
            negativeSign +
            (j ? i.substr(0, j) + thousands : '') +
            i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousands) +
            (decimalCount
                ? decimal +
                  Math.abs(amount - i)
                      .toFixed(decimalCount)
                      .slice(2)
                : '')
        );
    } catch (e) {
        console.log(e);
    }
}

function dateFormat(fmt, date) {
    let ret;
    const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
            fmt = fmt.replace(
                ret[1],
                ret[1].length == 1
                    ? opt[k]
                    : opt[k].padStart(ret[1].length, '0')
            );
        }
    }
    return fmt;
}

function submitProject(ldap, form, calculated, debugOnly) {
    let postURL = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/workflow/create`;
    let viewURL = `${process.env.VUE_APP_KANBAN_HOST}/#/project_request/view/${form.form_form_id}`;
    let attachmentLinks = form.file_list.map((file) => {
        return `<a target="_blank" href="${file.path}">${file.fileName}</a><br/><br/>`;
    });
    let attachmentSpecialApprovalLinks = form.special_approval_list.map(
        (file) => {
            return `<a target="_blank" href="${file.path}">${file.fileName}</a><br/><br/>`;
        }
    );
    let specialApprovalField = `${form.special_approval}<br/><br/>${attachmentSpecialApprovalLinks}`;
    let otherField = `<a target="_blank" href="${viewURL}">查看详细立项数据，请点击此链接</a><br/><br/>${attachmentLinks}`;
    let today = new Date();
    let mainTableData = [
        {
            name: 'requestname',
            value: '项目立项申请-项目类',
        },
        {
            name: 'requestlevel',
            value: '0',
        },
        {
            name: 'messageType',
            value: '0',
        },
        {
            name: 'xmlx',
            value: '0',
        },
        {
            name: 'xmbh',
            value: '',
        },
        {
            name: 'zq',
            value: form.billing_period,
        },
        {
            name: 'sfkyxm',
            value: form.is_pre_dev ? 0 : 1,
        },
        {
            name: 'khlx',
            value: '1',
        },
        {
            name: 'cplxxf',
            value: form.product_category[1] || '0',
        },
        {
            name: 'ywlxnew',
            value: form.business_type[0] || '0',
        },
        {
            name: 'sssyq',
            value: form.business_group_id || '0',
        },
        {
            name: 'lcfhd',
            value: form.process_compliance,
        },
        {
            name: 'sssyb',
            value: form.business_department_id,
        },
        {
            name: 'wbje',
            value: num45Filter(parseFloat(form.purchaseCostNum)) || '',
        },
        {
            name: 'khqcyw',
            value: '',
        },
        {
            name: 'yjscgm',
            value: form.est_market_size_over_20_million || '0',
        },
        {
            name: 'bubl',
            value: form.incomeDistribution[0].percentage || '0',
        },
        {
            name: 'xmmc',
            value: form.project_name,
        },
        {
            name: 'j',
            value: '100',
        },
        {
            name: 'qgcqxmd',
            value: form.defect_density,
        },
        {
            name: 'sssybfzr',
            value: '1',
        },
        {
            name: 'xkh',
            value: form.is_new_customer,
        },
        {
            name: 'khjc',
            value: form.customer_abrv_name || '',
        },
        {
            name: 'bbu',
            value: form.business_department_id || '0',
        },
        {
            name: 'yjcgje',
            value:
                num45Filter(parseFloat(form.outsourcingProjectCostNum)) || '',
        },
        {
            name: 'xmjl',
            value: form.project_manager_id || '0',
        },
        {
            name: 'lxbgrq',
            value: form.created_at || '',
        },
        {
            name: 'ssgjdq',
            value: form.customer_region_id || '',
        },
        {
            name: 'xsc',
            value: form.is_new_market,
        },
        {
            name: 'cplx',
            value: form.product_category[0] || '0',
        },
        {
            name: 'rjycffbcgl',
            value: form.one_time_release_success_rate || '0',
        },
        {
            name: 'yjgbcs',
            value: form.hardware_revision_count || '0',
        },
        {
            name: 'bghxmzq',
            value: '1',
        },
        {
            name: 'xfs',
            value: form.is_new_direction,
        },
        {
            name: 'gsmchtqs',
            value: form.corporation_id,
        },
        {
            name: 'bghxmksrq',
            value: '0',
        },
        {
            name: 'xmgy',
            value: form.project_summary.replace(/(\r\n|\n|\r)/g, '<br />'),
        },
        {
            name: 'ywlx',
            value: form.business_type[1] || '0',
        },
        {
            name: 'xmbgyysm',
            value:
                form.project_change_reason.replace(/(\r\n|\n|\r)/g, '<br />') ||
                '',
        },
        {
            name: 'khlb',
            value: '5',
        },
        {
            name: 'bghxmjsrq',
            value: '0',
        },
        {
            name: 'khdj',
            value: form.customer_level || '',
        },
        {
            name: 'xmzq',
            value: '1',
        },
        {
            name: 'xmksrq',
            value: form.project_start_date,
        },
        {
            name: 'xmjsrq',
            value: form.project_end_date,
        },
        {
            name: 'amswfzr',
            value: '1',
        },
        {
            name: 'sqlx',
            value: '3',
        },
        {
            name: 'xsry',
            value: form.sales_id,
        },
        {
            name: 'srqrfs',
            value: form.income_check_method,
        },
        {
            name: 'yjhtqsrq',
            value: form.est_contract_signing_date,
        },
        {
            name: 'onsiteoroffshore',
            value: form.entire_subcontract ? 3 : 4,
        },
        {
            name: 'bz',
            value: form.currency_id || '0',
        },
        {
            name: 'qtfj',
            value: '0',
        },
        {
            name: 'zshl',
            value: '13',
        },
        {
            name: 'yjzsryb',
            value: '13',
        },
        {
            name: 'yjzsrrmb',
            value: '13',
        },
        {
            name: 'yjztrrmb',
            value: '13',
        },
        {
            name: 'yjml',
            value: '13',
        },
        {
            name: 'yjmll',
            value: '13',
        },
        {
            name: 'zhmll',
            value: '13',
        },
        {
            name: 'yjztr',
            value: '13',
        },
        {
            name: 'yjptjbb',
            value: '2',
        },
        {
            name: 'xmzj',
            value: form.project_director_id,
        },
        {
            name: 'rjnrdsr',
            value: '4171',
        },
        {
            name: 'rjcb',
            value: '4171',
        },
        {
            name: 'gszt',
            value: '',
        },
        {
            name: 'tdr',
            value: '1',
        },
        {
            name: 'tdrq',
            value: dateFormat('YYYY-mm-dd', today),
        },
        {
            name: 'qt',
            value: otherField || '',
        },
        {
            name: 'xmjhps',
            value: '2020-09-25',
        },
        {
            name: 'xmzjyj',
            value: '2020-09-25',
        },
        {
            name: 'lxsybmc',
            value: '智能系统事业群（事业群）',
        },
        {
            name: 'xmwyhhq',
            value: '智能系统事业群（事业群）',
        },
        {
            name: 'sskh',
            value: form.customer_id,
        },
        {
            name: 'rjptbb',
            value: form.software_version,
        },
        {
            name: 'yjptbb',
            value: form.hardware_version,
        },
        {
            name: 'rjpt',
            value: form.software_platform,
        },
        {
            name: 'yjpt',
            value: '1',
        },
        {
            name: 'zqnew',
            value: form.project_period || '0',
        },
        {
            name: 'xmjb',
            value: form.project_level,
        },
        {
            name: 'zshl1',
            value: form.currency || '0',
        },
        {
            name: 'jdjhmb',
            value: '1',
        },
        {
            name: 'yjzsryb1',
            value: calculated.est_income_raw || '0',
        },
        {
            name: 'yjzsrrmb1',
            value: calculated.est_income || '0',
        },
        {
            name: 'yjztrrmb1',
            value: calculated.est_cost || '0',
        },
        {
            name: 'yjml1',
            value: calculated.profit || '0',
        },
        {
            name: 'yjmll1',
            value: calculated.profit_rate.toFixed() || '0',
        },
        {
            name: 'bgxmlx',
            value: '6',
        },
        {
            name: 'zhmll1',
            value: '6',
        },
        {
            name: 'yjptnew',
            value: form.hardware_platform,
        },
        {
            name: 'yjztr1',
            value: calculated.total_man_month || '0',
        },
        {
            name: 'srqrfsnew',
            value: form.income_check_method,
        },
        {
            name: 'rjnrdsr1',
            value: calculated.avg_income_RMB || '0',
        },
        {
            name: 'lxlclx',
            value: '0',
        },
        {
            name: 'lxlclxnew',
            value: '0',
        },
        {
            name: 'rjcb1',
            value: calculated.avg_cost_RMB || '0',
        },
        {
            name: 'lxsyq',
            value: form.business_department_id || '0',
        },
        {
            name: 'kz',
            value:
                specialApprovalField.replace(/(\r\n|\n|\r)/g, '<br />') || '',
        },
        {
            name: 'fjsc',
            value: '',
        },
        {
            name: 'xxaqjb',
            value: form.security_level,
        },
        {
            name: 'cswj',
            value: '',
        },
        {
            name: 'dd',
            value: form.deal_id || '',
        },
        {
            name: 'zjfcpzx',
            value: form.product || '',
        },
    ];
    let detailTableData = [
        // 项目阶段点计划
        form.stagePlans
            .filter((item) => item.id != 'total')
            .map((o) => {
                return [
                    { name: 'jddmc1', value: '' },
                    { name: 'jddmc', value: o.stage_name },
                    { name: 'px', value: '0' },
                    
                    { name: 'jdkssj', value: o.stage_start },
                    {
                        name: 'bjddtrrynew',
                        value: o.est_input_man_month || '0',
                    },
                    { name: 'jdjssj', value: o.stage_end },
                    { name: 'bjddtrry', value: o.est_input_man_month || '0' },
                    { name: 'bjddyjtrcbnew', value: o.est_input_cost || '0' },
                ];
            }),
        // 收入拆分表
        form.incomeDistribution.map((o) => { 
            let isMainProjectRow =
                o.implement_department_id === form.implement_department_id;
            let sumCost =
            isMainProjectRow ? 0
                : parseFloat(o.cost || '0') + parseFloat(o.history_cost || '0');
           
            return [
                { name: 'ssbm', value: o.implement_department_id },
                { name: 'ssbmbfb', value: o.percentage },
                { name: 'ssbmssrmb', value: o.income },
                {
                    name: 'ssbmyjrlcbrmb',
                    value:
                        o.implement_department_id ===
                        form.implement_department_id
                            ? 0
                            : sumCost || 0,
                },
                { name: 'ssbmyjcb', value: sumCost },
                { name: 'subxmmc', value: o.sub_project_name },
                {
                    name: 'xmglry',
                    value:
                        o.implement_department_id ===
                        form.implement_department_id
                            ? form.project_manager_id
                            : o.manager_id,
                },
            ];
        }),
    ];
    let data = {
        ldap_username: ldap,
        form_id: form.form_id,
        title: '立项申请-项目类',
        main_info: mainTableData,
        detail_info_list: detailTableData,
        workflow_id: process.env.VUE_APP_WORKFLOW_ID_PROJECT_REQUEST,
    };
    console.log(data);
    if (debugOnly) {
        return;
    }
    axios.post(postURL, data).then((response) => {
        if (response.data.code === 201 && response.data.data.request_id > 0) {
            localStorage.clear();
            // router.push({ name: 'list' });
            window.location.href = 'http://i.thundersoft.com/wui/main.jsp';
        } else if (response.data.msg_zh == 'success') {
            localStorage.clear();
            window.location.href = 'http://i.thundersoft.com/wui/main.jsp';
        } else {
            Message.error(response.data.msg_zh);
        }
    });
}

function changeProject(ldap, form, calculated, oldCalculated, hasOldForm) {
    let postURL = `${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/workflow/create`;
    let viewURL = `${process.env.VUE_APP_KANBAN_HOST}/#/project_request/view/${form.form_form_id}`;
    let attachmentLinks = form.file_list.map((file) => {
        return `<a target="_blank" href="${file.path}">${file.fileName}</a><br/><br/>`;
    });
    let attachmentSpecialApprovalLinks = form.special_approval_list.map(
        (file) => {
            return `<a target="_blank" href="${file.path}">${file.fileName}</a><br/><br/>`;
        }
    );
    let otherField = `<a target="_blank" href="${viewURL}">查看详细立项数据，请点击此链接</a><br>${attachmentLinks}`;
    let specialApprovalField = `${form.special_approval}<br/><br/>${attachmentSpecialApprovalLinks}`;
    let today = new Date();
    let mainTableData = [
        {
            name: 'requestname',
            value: '项目立项变更-项目类',
        },
        {
            name: 'requestlevel',
            value: '0',
        },
        {
            name: 'messageType',
            value: '0',
        },
        {
            name: 'xmlx',
            value: '0',
        },
        {
            name: 'xmbh',
            value: '',
        },
        {
            name: 'zq',
            value: form.billing_period,
        },
        {
            name: 'sfkyxm',
            value: form.is_pre_dev ? 0 : 1,
        },
        {
            name: 'khlx',
            value: '1',
        },
        {
            name: 'cplxxf',
            value: form.product_category[1] || '0',
        },
        {
            name: 'ywlxnew',
            value: form.business_type[0] || '0',
        },
        {
            name: 'sssyq',
            value: form.business_group_id || '0',
        },
        {
            name: 'lcfhd',
            value: form.process_compliance,
        },
        {
            name: 'sssyb',
            value: form.business_department_id,
        },
        {
            name: 'wbje',
            value: num45Filter(parseFloat(form.purchaseCostNum)) || '',
        },
        {
            name: 'khqcyw',
            value: '214',
        },
        {
            name: 'yjscgm',
            value: form.est_market_size_over_20_million || '0',
        },
        {
            name: 'bubl',
            value: form.incomeDistribution[0].percentage || '0',
        },
        {
            name: 'xmmc',
            value: form.project_name,
        },
        {
            name: 'bgxm',
            value: form.project_id,
        },
        {
            name: 'j',
            value: '100',
        },
        {
            name: 'qgcqxmd',
            value: form.defect_density,
        },
        {
            name: 'sssybfzr',
            value: '',
        },
        {
            name: 'xkh',
            value: form.is_new_customer,
        },
        {
            name: 'khjc',
            value: form.customer_abrv_name || '',
        },
        {
            name: 'bbu',
            value: form.business_department_id || '0',
        },
        {
            name: 'yjcgje',
            value:
                num45Filter(parseFloat(form.outsourcingProjectCostNum)) || '',
        },
        {
            name: 'xmjl',
            value: form.project_manager_id || '0',
        },
        {
            name: 'lxbgrq',
            value: form.created_at || '',
        },
        {
            name: 'ssgjdq',
            value: form.customer_region_id || '',
        },
        {
            name: 'xsc',
            value: form.is_new_market,
        },
        {
            name: 'cplx',
            value: form.product_category[0] || '0',
        },
        {
            name: 'rjycffbcgl',
            value: form.one_time_release_success_rate || '0',
        },
        {
            name: 'yjgbcs',
            value: form.hardware_revision_count || '0',
        },
        {
            name: 'bghxmzq',
            value: form.project_period || '0',
        },
        {
            name: 'xfs',
            value: form.is_new_direction,
        },
        {
            name: 'gsmchtqs',
            value: form.corporation_id,
        },
        {
            name: 'bghxmksrq',
            value: form.project_start_date || '',
        },
        {
            name: 'xmgy',
            value: form.project_summary.replace(/(\r\n|\n|\r)/g, '<br />'),
        },
        {
            name: 'ywlxxfnew',
            value: form.business_type[1] || '0',
        },
        {
            name: 'xmbgyysm',
            value:
                form.project_change_reason.replace(/(\r\n|\n|\r)/g, '<br />') ||
                '',
        },
        {
            name: 'khlb',
            value: '5',
        },
        {
            name: 'bghxmjsrq',
            value: form.project_end_date || '',
        },
        {
            name: 'khdj',
            value: form.customer_level || '',
        },
        {
            name: 'xmksrq',
            value: form.init_project_start_date,
        },
        {
            name: 'xmjsrq',
            value: form.init_project_end_date,
        },
        {
            name: 'amswfzr',
            value: '1',
        },
        {
            name: 'sqlx',
            value: '0',
        },
        {
            name: 'xsry',
            value: form.sales_id,
        },
        {
            name: 'srqrfs',
            value: form.income_check_method,
        },
        {
            name: 'yjhtqsrq',
            value: form.est_contract_signing_date,
        },
        {
            name: 'onsiteoroffshore',
            value: form.entire_subcontract ? 3 : 4,
        },
        {
            name: 'bz',
            value: form.currency_id || '0',
        },
        {
            name: 'qtfj',
            value: '0',
        },
        {
            name: 'zshl',
            value: '13',
        },
        {
            name: 'yjzsryb',
            value: '13',
        },
        {
            name: 'yjzsrrmb',
            value: '13',
        },
        {
            name: 'yjztrrmb',
            value: '13',
        },
        {
            name: 'yjml',
            value: '13',
        },
        {
            name: 'yjmll',
            value: '13',
        },
        {
            name: 'zhmll',
            value: '13',
        },
        {
            name: 'yjztr',
            value: '13',
        },
        {
            name: 'xmzj',
            value: form.project_director_id,
        },
        {
            name: 'rjnrdsr',
            value: '4171',
        },
        {
            name: 'rjcb',
            value: '4171',
        },
        {
            name: 'gszt',
            value: form.workhour_status || form.workhour_status  == 'None' ? '' : form.workhour_status,
        },
        {
            name: 'tdr',
            value: '1',
        },
        {
            name: 'tdrq',
            value: dateFormat('YYYY-mm-dd', today),
        },
        {
            name: 'qt',
            value: otherField || '',
        },
        {
            name: 'xmjhps',
            value: '2020-09-25',
        },
        {
            name: 'xmzjyj',
            value: '2020-09-25',
        },
        {
            name: 'lxsybmc',
            value: '智能系统事业群（事业群）',
        },
        {
            name: 'xmwyhhq',
            value: '智能系统事业群（事业群）',
        },
        {
            name: 'sskh',
            value: form.customer_id || '',
        },
        {
            name: 'rjptjbb',
            value: form.software_version || '',
        },
        {
            name: 'yjptjbb',
            value: form.hardware_version || '',
        },
        {
            name: 'rjpt',
            value: form.software_platform || '',
        },
        {
            name: 'yjpt',
            value: '1',
        },
        {
            name: 'xmjb',
            value: form.project_level,
        },
        {
            name: 'zshlnew',
            value: form.currency || '0',
        },
        {
            name: 'hj',
            value: 100,
        },
        {
            name: 'jdjhmb',
            value: '1',
        },
        {
            name: 'yjzsryb1',
            value: calculated.est_income_raw || '0',
        },
        {
            name: 'yjzsryb2',
            value: '0',
        },
        {
            name: 'yjzsrrmb1',
            value: calculated.est_income || '0',
        },
        {
            name: 'yjzsrrmb2',
            value: '0',
        },
        {
            name: 'yjztrrmb1',
            value: calculated.est_cost || '0',
        },
        {
            name: 'yjztrrmb2',
            value: '0',
        },
        {
            name: 'yjml1',
            value: calculated.profit || '0',
        },
        {
            name: 'yjmll1',
            value: calculated.profit_rate.toFixed() || '0',
        },
        {
            name: 'bgxmlx',
            value: '6',
        },
        {
            name: 'zhmll1',
            value: '6',
        },
        {
            name: 'yjptnew',
            value: form.hardware_platform || '',
        },
        {
            name: 'yjztr1',
            value: calculated.total_man_month || '0',
        },
        {
            name: 'srqrfsnew',
            value: form.income_check_method || '',
        },
        {
            name: 'rjnrdsr1',
            value: calculated.avg_income_RMB || '0',
        },
        {
            name: 'lxlclx',
            value: '0',
        },
        {
            name: 'lxlclxnew',
            value: '0',
        },
        {
            name: 'rjcb1',
            value: calculated.avg_cost_RMB || '0',
        },
        {
            name: 'lxsyq',
            value: form.business_department_id || '0',
        },
        {
            name: 'kz',
            value:
                specialApprovalField.replace(/(\r\n|\n|\r)/g, '<br />') || '',
        },
        {
            name: 'fjsc',
            value: '',
        },
        {
            name: 'xxaqjb',
            value: form.security_level || '',
        },
        {
            name: 'cswj',
            value: '',
        },
        {
            name: 'xmzq', // 立项项目周期
            value: form.oldProjectPeriod || '0',
        },
        {
            name: 'dd',
            value: form.deal_id || '',
        },
        // 立项 - 最大可能性
        {
            name: 'yjzsrybnew1', //预计总收入（原币）-立项
            value: num45Filter(parseFloat(oldCalculated.est_income_raw)) || '',
        },
        {
            name: 'yjzsrrmbnew1', //预计总收入（人民币）-立项
            value: num45Filter(parseFloat(oldCalculated.est_income)) || '',
        },
        {
            name: 'yjztrrmbnew1', //预计总投入（人民币）-立项
            value: num45Filter(parseFloat(oldCalculated.est_cost)) || '',
        },
        {
            name: 'yjmlnew1', //预计毛利（人民币）-立项
            value: num45Filter(parseFloat(oldCalculated.profit)) || '',
        },
        {
            name: 'yjmllnew1', //预计毛利率-立项
            value: Math.round(parseFloat(oldCalculated.profit_rate)) || 0 ,
        },
        {
            name: 'zhmllnew1', //综合毛利率-立项, hidden
            value: '',
        },
        {
            name: 'yjztrnew1', //预计总投入（人月）-立项
            value: num45Filter(parseFloat(oldCalculated.total_man_month)) || '',
        },
        {
            name: 'rjnrdsrnew1', //人均收入（人民币）--立项
            value:
                num45Filter(
                    oldCalculated.total_man_month == 0 ? 0 :
                    parseFloat(oldCalculated.est_income) /
                        parseFloat(oldCalculated.total_man_month)
                ) || '',
        },
        {
            name: 'rjcbnew1', //人均成本（人民币）-立项
            value: num45Filter(parseFloat(oldCalculated.avg_cost_RMB)) || '',
        },
        // 变更 - 变更后
        {
            name: 'yjzsrybnew2', //预计总收入（原币）-变更后
            value: num45Filter(parseFloat(calculated.est_income_raw)) || '',
        },
        {
            name: 'yjzsrrmbnew2', //预计总收入（人民币）-变更后
            value: num45Filter(parseFloat(calculated.est_income)) || '',
        },
        {
            name: 'yjztrrmbnew2', //预计总投入（人民币）-变更后
            value: num45Filter(parseFloat(calculated.est_cost)) || '',
        },
        {
            name: 'yjmlnew2', //预计毛利（人民币）-变更后
            value: num45Filter(parseFloat(calculated.profit)) || '',
        },
        {
            name: 'yjmllnew2', //预计毛利率-变更后
            value: Math.round(parseFloat(calculated.profit_rate)) || 0 ,
        },
        {
            name: 'zhmllnew3', //综合毛利率-变更后, hidden
            value: '',
        },
        {
            name: 'yjztrnew2', //预计总投入（人月）-变更后
            value: num45Filter(parseFloat(calculated.total_man_month)) || '',
        },
        {
            name: 'rjnrdsrnew2', //人均收入（人民币）-变更后
            value:
                num45Filter(
                    calculated.total_man_month == 0 ? 0 :
                    parseFloat(calculated.est_income) /
                        parseFloat(calculated.total_man_month)
                ) || '',
        },
        {
            name: 'rjcbnew2', //人均成本（人民币）-立项
            value: num45Filter(parseFloat(calculated.avg_cost_RMB)) || '',
        },
        // 变更 - 差异
        {
            name: 'yjzsrybnew3', //预计总收入（原币）-差异
            value:
                num45Filter(
                    parseFloat(calculated.est_income_raw) -
                        parseFloat(oldCalculated.est_income_raw)
                ) || '',
        },
        {
            name: 'yjzsrrmbnew3', //预计总收入（人民币）-差异
            value:
                num45Filter(
                    parseFloat(calculated.est_income) -
                        parseFloat(oldCalculated.est_income)
                ) || '',
        },
        {
            name: 'yjztrrmbnew3', //预计总投入（人民币）-差异
            value:
                num45Filter(
                    parseFloat(calculated.est_cost) -
                        parseFloat(oldCalculated.est_cost)
                ) || '',
        },
        {
            name: 'yjmlnew3', //预计毛利（人民币）-差异
            value:
                num45Filter(
                    parseFloat(calculated.profit) -
                        parseFloat(oldCalculated.profit)
                ) || '',
        },
        {
            name: 'yjmllnew3', //预计毛利率-差异
            value:
                Math.round(
                    parseFloat(calculated.profit_rate) -
                        parseFloat(oldCalculated.profit_rate)
                    )  || 0,
        },
        {
            name: 'zhmllnew3', //综合毛利率-差异, hidden
            value: '',
        },
        {
            name: 'yjztrnew3', //预计总投入（人月）-差异
            value:
                num45Filter(
                    parseFloat(calculated.total_man_month) -
                        parseFloat(oldCalculated.total_man_month)
                ) || '',
        },
        {
            name: 'rjnrdsrnew3', //人均收入（人民币）-差异
            value:
                num45Filter(
                    (calculated.total_man_month == 0 ? 0 :
                        parseFloat(calculated.est_income) /
                            parseFloat(calculated.total_man_month)) -
                            (oldCalculated.total_man_month == 0 ? 0 :
                            parseFloat(oldCalculated.est_income) /
                                parseFloat(oldCalculated.total_man_month))
                ) || '',
        },
        {
            name: 'rjcbnew3', //人均成本（人民币）-差异
            value:
                num45Filter(
                    parseFloat(calculated.avg_cost_RMB) -
                        parseFloat(oldCalculated.avg_cost_RMB)
                ) || '',
        },
    ];
    let stagePlansData;
    let incomeDistributionData;
    // 项目阶段点计划
    stagePlansData = form.stagePlans
        .filter((item) => item.id != 'total')
        .map((o) => {
            return [
                {
                    name: 'jddmc1',
                    value: '',
                },
                {
                    name: 'jddmc',
                    value: o.stage_name ,
                },
                {
                    name: 'px',
                    value: '0',
                },
                {
                    name: 'jdkssj',
                    value: o.stage_start,
                },
                {
                    name: 'bjddtrrynew',
                    value: o.est_input_man_month || '0',
                },
                {
                    name: 'jdjssj',
                    value: o.stage_end,
                },
                {
                    name: 'bjddtrry',
                    value: o.est_input_man_month || '0',
                },
                {
                    name: 'bjddyjtrcb',
                    value: o.est_input_cost || '0',
                },
            ];
        });
    // 收入拆分表
    if (hasOldForm === true) {
        incomeDistributionData = form.incomeDistribution.map((o) => {
            let estIncome = '';
            let subProjectName = '';
            let subProjectId = '';
            let manager = '';
            let isMainProjectRow =
                o.implement_department_id === form.implement_department_id;
            if (form.enableSubProjectName) {
                estIncome = isMainProjectRow
                    ? 0
                    : num45Filter(
                        parseFloat(o.cost || '0') +
                        parseFloat(o.history_cost, '0')
                ) || 0; 
                subProjectName =
                    o.sub_project_id === null || o.sub_project_id == undefined ? o.sub_project_name : '';
                subProjectId =
                o.sub_project_id === null || o.sub_project_id == undefined  ?  '' : o.sub_project_id;
                manager = isMainProjectRow
                    ? form.project_manager_id
                    : o.manager_id;
            }
            // 在任何情况下, 如果子项目实施部门和立项部门一样, Sub项目名称传id
            if (isMainProjectRow) {
                subProjectId = o.sub_project_id;
            }
            return [
                {
                    name: 'ssbm',
                    value: o.implement_department_id,
                },
                {
                    name: 'ssbmbfb',
                    value: o.percentage,
                },
                {
                    name: 'ssbmsrrmb', // 实施部门收入（人民币）
                    value: o.income,
                },
                {
                    name: 'ssbmyjcb', // 实施部门预计成本（人民币）
                    value: estIncome,
                },
                {
                    name: 'subxmmc', // 新建Sub项目名称
                    value: subProjectName,
                },
                {
                    name: 'subllk', // Sub项目名称
                    value: subProjectId,
                },
                {
                    name: 'gsglry', // 工时管理人员
                    value: manager,
                },
            ];
        });
    } else {
        incomeDistributionData = form.incomeDistribution.map((o) => {
            return [
                {
                    name: 'ssbm',
                    value: o.implement_department_id,
                },
                {
                    name: 'ssbmbfb',
                    value: o.percentage,
                },
                {
                    name: 'ssbmssrmb',
                    value: o.income,
                },
                {
                    name: 'ssbmyjrlcbrmb',
                    value:
                        o.implement_department_id ===
                        form.implement_department_id
                            ? 0
                            : o.cost || 0,
                },
                {
                    name: 'subxmmc',
                    value: o.sub_project_name,
                },
                {
                    name: 'xmglry',
                    value:
                        o.implement_department_id ===
                        form.implement_department_id
                            ? form.project_manager_id
                            : o.manager_id,
                },
            ];
        });
    }
    let detailTableData = [stagePlansData, incomeDistributionData];
    // 2021-02-20 如果立项数据由看板生成, 提交到新的OA流程5341
    let workflowId;
    if (hasOldForm === true) {
        console.log('new workflow');
        workflowId = process.env.VUE_APP_WORKFLOW_ID_PROJECT_CHANGE_NEW;
        mainTableData.push({
            name:'zjsjfzx',
            value: form.product || ''
        })
    } else {
        console.log('old workflow');
        workflowId = process.env.VUE_APP_WORKFLOW_ID_PROJECT_CHANGE;
        mainTableData.push({
            name:'zjscpzx',
            value: form.product || ''
        })
    }
    let data = {
        ldap_username: ldap,
        form_id: form.form_id,
        title: '立项变更-项目类',
        main_info: mainTableData,
        detail_info_list: detailTableData,
        workflow_id: workflowId,
    };
    console.log(data);
    axios.post(postURL, data).then((response) => {
        if (response.data.code === 201 && response.data.data.request_id > 0) {
            localStorage.clear();
            // router.push({ name: 'list' });
            window.location.href = 'http://i.thundersoft.com/wui/main.jsp';
        } else if (response.data.msg_zh === 'success') {
            localStorage.clear();
            window.location.href = 'http://i.thundersoft.com/wui/main.jsp';
        } else {
            Message.error(response.data.msg_zh);
        }
    });
}

export { submitProject, changeProject };
